import React, { useEffect, useState } from "react";
import { ListRawState } from "../../types";
import { deleteListByID, editListByID, fetchList } from "../../api";
import { Table, Button, Space, Modal, Row, Col, Input, Select, message as antdMessage } from "antd";
import axios from "axios";
import { useLocation, useSearchParams } from "react-router-dom";


const Index: React.FC = () => {
  const types = ["全部","已下单", "已付款", "未发货", "已发货", "待收货", "已收货"]
  // 0. 获取地址栏参数
  const [searchParams, setSearchParams] = useSearchParams();
  const wd = searchParams.get('wd');
  const type = searchParams.get('type') || '全部'
  // 1. 数据请求
  const [list, setList] = useState<ListRawState[]>([]);

  const getList = async () => {
    console.log(123)
    const params = {
      wd: wd || "",
      type: type || '全部'
    }
    const resp = await fetchList(params);
    setList(resp.data.data);
  };

  useEffect(() => {
    getList();
  }, [wd, type]);

  // 5. 多项删除id
  const [selectIDs, setSelectIDS] = useState("");
  // 2. 数据渲染
  const columns = [
    {
      title: "id",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "电话",
      dataIndex: "tel",
      key: "tel",
    },
    {
      title: "地址",
      dataIndex: "address",
      key: "address",
    },
    {
      title: "图片",
      dataIndex: "image",
      key: "image",
      render(text: string) {
        return <img src={text} alt="" height={50} />;
      },
    },
    {
      title: "状态",
      dataIndex: "type",
      key: "type",
    },
    {
      title: selectIDs.length ? <Button
        type="primary"
        danger
        onClick={() => handleSelectDelete(selectIDs)}
      >
        批量删除
      </Button> : '操作',
      key: "opration",
      render(record: ListRawState) {
        return (
          <Space>
            <Button type="primary" onClick={() => openModal(record)}>编辑</Button>
            <Button type="primary" danger onClick={() => handleDelete(record)}>
              删除
            </Button>
          </Space>
        );
      },
    },
  ];
  // 3. 分页设置
  const pagination = {
    defaultPageSize: 5,
  };
  // 4. 删除事件
  const handleDelete = (record: ListRawState) => {
    // 二次确认
    Modal.confirm({
      title: "警告",
      content: "确认要删除该项数据吗?",
      okText: "确认",
      cancelText: "取消",
      // 确定按钮回调事件
      async onOk() {
        // 获取删除id
        const id = record.id;
        // 发送删除请求
        const resp = await deleteListByID(id);
        // 保存数据
        setList(resp.data.data);
      },
      onCancel() { },
    });
  };

  // 6. 批量删除函数
  const handleSelectDelete = (ids: string) => {
    // 二次确认
    Modal.confirm({
      title: "警告",
      content: "确认要删除选中项目数据吗?",
      okText: "确认",
      cancelText: "取消",
      // 确定按钮回调事件
      async onOk() {
        // 发送删除请求
        const resp = await deleteListByID(ids);
        // 保存数据
        setList(resp.data.data);
        setSelectIDS('')
      },
      onCancel() { },
    });
  };
  //  7. 当前正在修改的数据
  const [editData, setEditData] = useState<ListRawState>({
    id: '',
    tel: 1,
    address: "2",
    name: "3",
    image: "4",
    type: '5'
  })
  // 8. 弹框状态
  const [isOpen, setIsOpen] = useState(false)
  // 9. 打开和关闭
  const openModal = (record: ListRawState) => {
    setIsOpen(true)
    // 数据回显
    setEditData(record)
  }
  const closeModal = () => setIsOpen(false)
  // 10. 确定修改
  const handleEdit = async () => {
    if (/^1[3-9]\d{9}$/.test(editData.tel.toString())) {
      const resp = await editListByID(editData);
      setList(resp.data.data)
      closeModal();
    } else {
      antdMessage.error('手机号格式不正确')
    }
  }
  // 11. 搜索函数

  const handleSearch = (value: string) => {
    if(value) searchParams.set('wd', value);

    const o: any = {};
    if(value) o.wd = value;
    if(type) o.type = type
    setSearchParams(o)

  }
  const handleClick = (v: string) => {
    if(v) searchParams.set('type', v);
    const o: any = {};
    if(wd) o.wd = wd;
    if(v) o.type = v
    setSearchParams(o)
  }
  return (
    <div>
      {/* 查询 */}
      <Row className="my-row">
        <Col span={2}>搜索：</Col>
        <Col span={22}>
          <Input.Search defaultValue={wd || ''} onSearch={value => handleSearch(value)}></Input.Search>
        </Col>
      </Row>
      <Row className="my-row">
        <Col span={2}>状态：</Col>
        <Col span={22}>
         <Space>
         {
            types.map((v, i) => {
              return <Button key={i} type={v === type ? 'primary': "default"} onClick={() => handleClick(v)}>{v}</Button>
            })
        }
         </Space>
        </Col>
      </Row>

      {/* 表格 */}
      <Table
        dataSource={list}
        columns={columns}
        pagination={pagination}
        rowKey="id"
        rowSelection={{
          onChange(selectedRowKeys) {
            // 只需要保存删除的id
            const ids = selectedRowKeys.join(",");
            setSelectIDS(ids);
          },
        }}
      ></Table>

      {/* 弹框 */}
      <Modal open={isOpen} okText="确定" cancelText="取消" onOk={() => handleEdit()} onCancel={() => closeModal()}>
        <div>
          <Row className="my-row">
            <Col span={2}>ID:</Col>
            <Col span={21}>
              <Input value={editData.id} onChange={e => {
                setEditData({
                  ...editData,
                  id: e.target.value
                })
              }} disabled></Input>
            </Col>
          </Row>
          <Row className="my-row">
            <Col span={2}>姓名:</Col>
            <Col span={21}>
              <Input value={editData.name} onChange={e => {
                setEditData({
                  ...editData,
                  name: e.target.value
                })
              }}></Input>
            </Col>
          </Row>
          <Row className="my-row">
            <Col span={2}>电话:</Col>
            <Col span={21}>
              <Input value={editData.tel} onChange={e => {
                setEditData({
                  ...editData,
                  tel: +e.target.value
                })
              }}></Input>
            </Col>
          </Row>
          <Row className="my-row">
            <Col span={2}>地址:</Col>
            <Col span={21}>
              <Input value={editData.address} onChange={e => {
                setEditData({
                  ...editData,
                  address: e.target.value
                })
              }}></Input>
            </Col>
          </Row>
          <Row className="my-row">
            <Col span={2}>状态:</Col>
            <Col span={21}>
              <Select style={{ width: '100%' }} value={editData.type} onChange={(value) => {
                setEditData({
                  ...editData,
                  type: value
                })
              }}>
                {
                  ["已下单", "已付款", "未发货", "已发货", "待收货", "已收货"].map((v, i) => {
                    return <Select.Option key={i} value={v}>{v}</Select.Option>
                  })
                }
              </Select>
            </Col>
          </Row>
          <Row className="my-row">
            <Col span={2}>图片:</Col>
            <Col span={21}>
              <Input value={editData.image} onChange={e => {
                setEditData({
                  ...editData,
                  image: e.target.value
                })
              }}></Input>
            </Col>
          </Row>
        </div>
      </Modal>
    </div>
  );
};

export default Index;

// 多项删除
// 前端获取删除的id

// 后端根据id删除

// axios.delete("/api/12313", {
//   params: {
//     id: "123456,567885,1231231231"
//   },
// });

// list = [{
//   id: 'a'
// },{
//   id: 'b'
// },{
//   id: 'c'
// },{
//   id: 'd'
// },{
//   id: 'f'
// },{
//   id: 'g'
// }]

// list = list.filter(v => {
//   return !id.includes(v.id)
// })

// id = "a,b,c"
